<?php
/**
 * Bos 图片上传
 *
 * Author: Zeon
 * Date: 2018/1/27
 * Created by Panxsoft.
 */
namespace App\Http\Controllers\Api\V1\App\Common;

use App\Http\Controllers\ApiController;
use App\Services\Utils\ImageHelper;
use App\Services\Utils\OSSable;
use App\Services\Utils\UploadFile;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;

class FileManagerController extends ApiController
{
    use UploadFile,
        OSSable;

    const DEFAULT_DIR_PREFIX = 'uploads/';

    /**
     * 上传
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function store(Request $request)
    {
        $url = $this->uploadFileToUrl($request->file, $this->getSavePath($request->name, $request->dir));

        return $this->response(compact('url'));
    }

    private function getSavePath($name, $dir): ?string
    {
        return null;
    }

    /**
     * @param UploadedFile $file
     * @param string $save_path
     *
     * @return mixed
     * @throws \Exception
     */
    private function uploadFileToUrl(UploadedFile $file, ?string $save_path): string
    {
        $key = $this->uploadPostFileByDriver($file, $save_path);

        $url = $this->getStaticUrl($key);

        return $url;
    }

    /**
     * @param UploadedFile $file
     * @param string $save_path
     *
     * @return string
     * @throws \Exception
     */
    private function uploadPostFileByDriver(UploadedFile $file): string
    {
        require_once(base_path('../dw-oc/admin/config.php'));

        if (defined('CK_FINDER_BACKEND') && CK_FINDER_BACKEND === ImageHelper::CK_FINDER_OSS) { // oss图片驱动
            $key = $this->uploadPostFile($file, self::DEFAULT_DIR_PREFIX);
        } else { // file 图片驱动
            $key = $this->uploadPostFileToFile($file, self::DEFAULT_DIR_PREFIX);
        }

        return ImageHelper::generateImagePath($key);
    }
}
